package net.dgg.zz.api.credential.service;

import net.dgg.framework.tac.utils.DggValidateUtil;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserManager;
import net.dgg.zz.api.credential.entity.SimpleGeneralCertificate;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.entity.Product;
import net.dgg.zz.common.service.ProductService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.ValidateUtils;
import net.dgg.zz.credential.baseCredential.dao.BaseCredentialDao;
import net.dgg.zz.credential.baseCredential.entity.BaseCredential;
import net.dgg.zz.credential.capitalPoolCount.service.CapitalPoolCountService;
import net.dgg.zz.credential.certificateProduct.service.CertificateProductService;
import net.dgg.zz.credential.excption.CertificateExcption;
import net.dgg.zz.credential.generalCredential.dao.GeneralCertificateDao;
import net.dgg.zz.credential.generalCredential.entity.GeneralCertificate;
import net.dgg.zz.credential.generalCredential.service.GeneralCredentialService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 证书对外接口service
 *
 * @author Administrator
 * @date 2018/9/13 0013
 */
@Service
public class GeneralCredentialApiService extends BaseService {


    @Resource
    private GeneralCredentialService generalCredentialService;

    @Resource
    private ProductService productService;

    @Resource
    private UserManager userManager;

    @Resource
    private SystemRecordService systemRecordService;

    @Resource
    private CapitalPoolCountService capitalPoolCountService;

    @Resource
    private CertificateProductService certificateProductService;

    @Resource
    private GeneralCertificateDao generalCertificateDao;
    @Resource
    private BaseCredentialDao baseCredentialDao;

    /**
     * 证书费用申请状态修改
     *
     * @param orderId
     * @param userId
     * @param type
     */
    @Transactional

    public void updateProductCostState(Long orderId, Long userId, Integer type) {
        ValidateUtils.isTrue(StringUtils.isNotEmpty(orderId), CertificateExcption.class, "销售子订单id不能为空！");
        ValidateUtils.isTrue(StringUtils.isNotEmpty(userId), CertificateExcption.class, "修改人的id不能为空！");
        ValidateUtils.isTrue(StringUtils.isNotEmpty(userId), CertificateExcption.class, "修改人的id不能为空！");
        UserEntity user = userManager.findUserById(userId);
        ValidateUtils.isTrue(StringUtils.isNotEmpty(user), CertificateExcption.class, "审核人不存在！");
        Product product = productService.findProductByOrderId(orderId, null);
        DggValidateUtil.isTrue(StringUtils.isNotEmpty(product), CertificateExcption.class, "销售子订单不存在,请核对");

        if (StringUtils.isEmpty(product.getCostState()) || !product.getCostState().equals(ScProductConstant.ALREADY_PAY)) {
            product.setCostState(ScProductConstant.NOT_PAY);
        }
        product.setUpdaterUser(user);
        productService.updateProduct(product);

        GeneralCertificate generalCertificate = generalCredentialService.findCredentialByScOrderId(product.getScProductOrderId());
        // 保存操作日志
        SystemRecord systemRecords = new SystemRecord();
        systemRecords.setWorkTableName("zzsc_product");
        systemRecords.setWorkId(product.getId());
        systemRecords.setWorkNo(product.getOrderBusinessNo());
        if (!StringUtils.isEmpty(generalCertificate)) {
            systemRecords.setSource("1");
            systemRecords.setCertificateCode(generalCertificate.getCertificateNo());
            systemRecords.setCertificateType(generalCertificate.getCertificateType());
            systemRecords.setCertificateName(generalCertificate.getCertificateName());
            systemRecords.setSignOrgId(generalCertificate.getSignOrgId());
            systemRecords.setSignOrgName(generalCertificate.getSignOrgName());
        } else {
            systemRecords.setSource("2");
            systemRecords.setSignOrgId(product.getProductOrgId());
            systemRecords.setSignOrgName(product.getProductOrgName());
        }
        if (type == 1) {
            systemRecords.setOperateType("4");
            systemRecords.setRemarks("提交费用申请");

        } else {
            systemRecords.setOperateType("6");
            systemRecords.setRemarks("费用申请审核不通过");
        }
        systemRecordService.apiSave(systemRecords, user);
    }

    /**
     * 证书财务信息修改
     * @param orderId
     * @param userId
     * @param deposit
     * @param depositPayTime
     * @param tailMoney
     * @param tailMoneyPayTime
     * @param accountMoney
     * @param currentApplyMoney
     */
    @Transactional
    public void updateCredentialFinance(Long orderId, Long userId, BigDecimal deposit, Date depositPayTime, BigDecimal tailMoney, Date tailMoneyPayTime, BigDecimal accountMoney, BigDecimal currentApplyMoney) {
        ValidateUtils.isTrue(StringUtils.isNotEmpty(orderId), CertificateExcption.class, "销售子订单id不能为空！");
        ValidateUtils.isTrue(StringUtils.isNotEmpty(userId), CertificateExcption.class, "通过审核人的id！");
        ValidateUtils.isTrue(StringUtils.isNotEmpty(accountMoney), CertificateExcption.class, "打款费用不能为空！");
        UserEntity user = userManager.findUserById(userId);
        ValidateUtils.isTrue(StringUtils.isNotEmpty(user), CertificateExcption.class, "审核人不存在！");

        Product product = productService.findProductByOrderId(orderId, null);
        Map map = certificateProductService.findOrderInfoByOrderNo(product.getOrderBusinessNo());
        // 保存操作日志
        SystemRecord systemRecords = new SystemRecord();
        systemRecords.setSource("2");
        systemRecords.setOperateType("5");
        systemRecords.setWorkTableName("zzsc_product");
        systemRecords.setWorkId(product.getId());
        systemRecords.setWorkNo(product.getOrderBusinessNo());
        // 如果该费用申请关联的证书还是管理的它的话就去修改证书的信息
        GeneralCertificate generalCertificate = new GeneralCertificate();
        if (StringUtils.isNotEmpty(map) && map.get("orderNo").toString().equals(product.getOrderBusinessNo())) {
            generalCertificate = generalCertificateDao.selectByPrimaryKey(Long.parseLong(map.get("certificateId").toString()));
            generalCertificate.setDepositPayTime(StringUtils.isNotEmpty(depositPayTime) ? depositPayTime : generalCertificate.getDepositPayTime());
            generalCertificate.setDeposit(StringUtils.isNotEmpty(deposit) ? deposit : generalCertificate.getDeposit());
            generalCertificate.setTailMoney(StringUtils.isNotEmpty(tailMoney) ? tailMoney : generalCertificate.getTailMoney());
            generalCertificate.setTailMoneyPayTime(StringUtils.isNotEmpty(tailMoneyPayTime) ? tailMoneyPayTime : generalCertificate.getTailMoneyPayTime());
            generalCertificate.setAccountMoney(accountMoney);
            generalCertificate.setUpdaterUser(user);
            generalCertificateDao.updateByPrimaryKeySelective(generalCertificate);
            baseCredentialDao.updateByPrimaryKeySelective(generalCertificate);
            // 将费用申请信息添加到资源池中
            ValidateUtils.isTrue(StringUtils.isNotEmpty(currentApplyMoney), CertificateExcption.class, "费用申请金额不能为空！");
            BaseCredential baseCredential = new BaseCredential();
            baseCredential.setId(generalCertificate.getBaseId());
            baseCredential.setCertificateNo(generalCertificate.getCertificateNo());
            baseCredential.setSignOrgId(generalCertificate.getSignOrgId());
            baseCredential.setSignOrgName(generalCertificate.getSignOrgName());
            baseCredential.setGeneralType(generalCertificate.getGeneralType());
            capitalPoolCountService.addCapitalPoolCountRecord(baseCredential, user, currentApplyMoney, 0, orderId);

            // 保存操作日志
            SystemRecord systemRecord = new SystemRecord();
            systemRecord.setSource("1");
            systemRecord.setOperateType("5");
            systemRecord.setWorkTableName("zz_general_certificate");
            systemRecord.setWorkId(generalCertificate.getBaseId());
            systemRecord.setCertificateName(generalCertificate.getCertificateName());
            systemRecord.setCertificateCode(generalCertificate.getCertificateNo());
            systemRecord.setWorkNo(generalCertificate.getCertificateNo());
            systemRecord.setSignOrgId(generalCertificate.getSignOrgId());
            systemRecord.setSignOrgName(generalCertificate.getSignOrgName());
            systemRecord.setCertificateType(generalCertificate.getCertificateType());
            systemRecord.setRemarks("证书中心：证书费用申请通过修改金额");
            systemRecordService.apiSave(systemRecord, user);


            systemRecords.setCertificateCode(generalCertificate.getCertificateNo());
            systemRecords.setCertificateType(generalCertificate.getCertificateType());
            systemRecords.setCertificateName(generalCertificate.getCertificateName());
            systemRecords.setSignOrgId(generalCertificate.getSignOrgId());
            systemRecords.setSignOrgName(generalCertificate.getSignOrgName());
            systemRecords.setRemarks("证书中心：证书费用申请通过修改金额,修改销售子订单状态");
        } else {
            systemRecords.setSignOrgId(product.getProductOrgId());
            systemRecords.setSignOrgName(product.getProductOrgName());
            systemRecords.setCertificateType(generalCertificate.getCertificateType());
            systemRecords.setCertificateCode(generalCertificate.getCertificateNo());
            systemRecords.setCertificateName(generalCertificate.getCertificateName());
            systemRecords.setRemarks("证书费用申请通过修改金额,修改销售子订单状态");
            capitalPoolCountService.addCapitalPoolCountRecord(null, user, currentApplyMoney, 0, orderId);

        }
        product.setTheDeposit(StringUtils.isNotEmpty(deposit) ? deposit : generalCertificate.getDeposit());
        product.setTheDepositTime(StringUtils.isNotEmpty(depositPayTime) ? depositPayTime : generalCertificate.getDepositPayTime());
        product.setBalancePayment(StringUtils.isNotEmpty(tailMoney) ? tailMoney : generalCertificate.getTailMoney());
        product.setBalancePaymentTime(StringUtils.isNotEmpty(tailMoneyPayTime) ? tailMoneyPayTime : generalCertificate.getTailMoneyPayTime());
        product.setCostState(ScProductConstant.ALREADY_PAY);
        product.setUpdaterUser(user);
        productService.updateProduct(product);
        systemRecordService.apiSave(systemRecords, user);

    }

    /**
     * 查询证书列表信息并分页
     * @param params
     * @return
     */
    public List<SimpleGeneralCertificate> listCredential(Map params){
        return generalCertificateDao.listCredentialWithPage(params);
    }
}
